//
//  SetupViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/29.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "SetupViewController.h"
#import "EditNameViewController.h"
#import "ResetViewController.h"
#import "LCChatKitExample.h"
#import "EditPhoneViewController.h"
#import "BindingViewController.h"

@interface SetupViewController () <TZImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet YYAnimatedImageView *iconImageView;

@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;

@property (weak, nonatomic) IBOutlet UILabel *accountLabel;

@property (nonatomic, copy) NSString *pName;

@property (nonatomic, copy) NSString *cName;

@end

@implementation SetupViewController

BOOL one = NO;
BOOL two = NO;

- (instancetype)init
{
    self = [super init];
    if (self) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"SetupViewController" bundle:[NSBundle mainBundle]];
        self = [sb instantiateInitialViewController];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getMyInfo];
    
    MJWeakSelf;
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        [weakSelf getMyInfo];
    }];
}


#pragma mark - 请求个人信息
- (void)getMyInfo {
    
    one = NO;
    two = NO;
    
    AVUser *user = [AVUser currentUser];
    
    [self.iconImageView setImageWithURL:[NSURL URLWithString:[user objectForKey:kavatarURL]] placeholder:[UIImage imageNamed:@"lcck_conversation_placeholder_avatar"]];
    
    self.userNameLabel.text = user.username;
    
    self.phoneLabel.text = user.mobilePhoneNumber;
    
    AVQuery *query = [AVQuery queryWithClassName:kRelationship];
    
    [query whereKey:kUsername equalTo:user.username];
    
    
    MJWeakSelf;
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        if (!error) {
            [weakSelf.tableView.mj_header endRefreshing];
            
            if (objects.count > 0) {
                
                
                void(^onlyParent)() = ^(){
                    
                    NSString *pObjectId = [[objects[0] objectForKey:kParent] objectForKey:kobjectId];
                    
                    AVQuery *pQuery = [AVQuery queryWithClassName:kUser];
                    [pQuery whereKey:kobjectId equalTo:pObjectId];
                    
                    [pQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                        if (objects.count > 0) {
                            
                            //查到父账号的名字
                            weakSelf.pName = [objects[0] objectForKey:kUsername];
                            
                            one = YES;
                            
                            weakSelf.accountLabel.text = NSStringFormat(@"父账号：%@",weakSelf.pName);
                            
                            if (weakSelf.pName.length > 0 && weakSelf.cName.length > 0) {
                                weakSelf.accountLabel.text = NSStringFormat(@"父账号：%@  子账号：%@",weakSelf.pName, weakSelf.cName);
                            }
                            
                        } else {
                            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                        }
                    }];
                };
                void(^onlyChildren)() = ^(){
                    
                    NSString *pObjectId = [[objects[0] objectForKey:kChildren] objectForKey:kobjectId];
                    
                    AVQuery *pQuery = [AVQuery queryWithClassName:kUser];
                    [pQuery whereKey:kobjectId equalTo:pObjectId];
                    
                    [pQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                        if (objects.count > 0) {
                            
                            //查到子账号的名字
                            weakSelf.cName = [objects[0] objectForKey:kUsername];
                            
                            two = YES;
                            
                            weakSelf.accountLabel.text = NSStringFormat(@"子账号：%@",weakSelf.cName);
                            
                            if (weakSelf.pName.length > 0 && weakSelf.cName.length > 0) {
                                weakSelf.accountLabel.text = NSStringFormat(@"父账号：%@  子账号：%@",weakSelf.pName, weakSelf.cName);
                            }
                            
                        } else {
                            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                        }
                        
                    }];
                };
                
                
                if ([objects[0] objectForKey:kParent] && ![objects[0] objectForKey:kChildren]) {
                    //仅绑定了父账号
                    two = YES;
                    onlyParent();
                    
                } else if ([objects[0] objectForKey:kChildren]  && ![objects[0] objectForKey:kParent]) {
                    //仅绑定了子账号
                    one = YES;
                    onlyChildren();
                    
                } else if([objects[0] objectForKey:kChildren]  && [objects[0] objectForKey:kParent]) {
                    //都绑定了
                    onlyParent();
                    onlyChildren();
                } else {
                    one = YES;
                    two = YES;
                    weakSelf.accountLabel.text = @"未绑定任何账号";
                }
                
            } else {
                one = YES;
                two = YES;
                weakSelf.accountLabel.text = @"未绑定任何账号";
            }
            
        } else {
            [weakSelf.tableView.mj_header endRefreshing];
            [LCCKUtil showNotificationWithTitle:@"账号关系查询失败" subtitle:nil type:LCCKMessageNotificationTypeError];
        }
    }];
}


#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AVUser *user = [AVUser currentUser];
    
    if (indexPath.section == 0) {
        
        switch (indexPath.row) {
            case 0:
                NSLog(@"头像");
                
                [self modifyWithIcon];
                
                break;
                
            case 1: {
                NSLog(@"昵称");
                
            }
                break;
                
            case 2: {
                NSLog(@"手机号码");
                
                EditPhoneViewController *vc = [EditPhoneViewController new];
                
                MJWeakSelf;
                vc.editPhoneBlock = ^(NSString *phone){
                    
                    weakSelf.phoneLabel.text = phone;
                };
                
                [self.navigationController pushViewController:vc animated:YES];
                
            }
                break;
                
            case 3: {
                NSLog(@"修改密码");
                
                ResetViewController *vc = [ResetViewController new];
                vc.phone = user.mobilePhoneNumber;
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            case 4: {
                NSLog(@"绑定账号");
                
                if (one && two ) {
                    BindingViewController *vc = [BindingViewController new];
                    
                    vc.pName = self.pName;
                    vc.cName = self.cName;
                    
                    MJWeakSelf;
                    void(^updateStatus)() = ^(){
                        
                        if (weakSelf.pName.length > 0 && weakSelf.cName.length == 0) {
                            weakSelf.accountLabel.text = NSStringFormat(@"父账号：%@",weakSelf.pName);
                        } else if (weakSelf.cName.length > 0 && weakSelf.pName.length == 0) {
                            weakSelf.accountLabel.text = NSStringFormat(@"子账号：%@",weakSelf.cName);
                        } else if (weakSelf.pName.length > 0 && weakSelf.cName.length > 0) {
                            weakSelf.accountLabel.text = NSStringFormat(@"父账号：%@  子账号：%@",weakSelf.pName, weakSelf.cName);
                        } else {
                            weakSelf.accountLabel.text = NSStringFormat(@"未绑定任何账号");
                        }
                        
                        [LCCKUtil hideProgress];
                    };
                    
                    //绑定账号
                    vc.bindingBlock = ^(NSString *name){
                        
                        weakSelf.cName = name;
                        
                        updateStatus();
                        [[NSNotificationCenter defaultCenter] postNotificationName:kBindingWithNotification object:nil];
                    };
                    
                    //解绑账号
                    vc.removeBindingBlock = ^(){
                        
                        weakSelf.cName = @"";
                        
                        [[NSNotificationCenter defaultCenter] postNotificationName:kRemoveBindingWithNotification object:nil];
                        
                        updateStatus();
                    };
                    
                    [self.navigationController pushViewController:vc animated:YES];
                } else {
                    [LCCKUtil showNotificationWithTitle:@"等待网络请求，稍等片刻,可以下拉刷新试试" subtitle:nil type:LCCKMessageNotificationTypeWarning];
                }
            }
                break;
                
            default:
                break;
        }
        
    } else if (indexPath.section == 1) {
        NSLog(@"退出登录");
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kInvalidateTimer object:nil];
        [LCChatKitExample signOutFromViewController:self];
    }
}


#pragma mark - 修改头像
- (void)modifyWithIcon {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    
    
    void(^updateWithContact)(NSString *) = ^(NSString *url){
        
        AVQuery *query = [AVQuery queryWithClassName:kContact];
        
        [query whereKey:kUsername equalTo:[AVUser currentUser].username];
        
        [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            
            if (!error) {
                
                [objects enumerateObjectsUsingBlock:^(AVObject *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    [obj setObject:url forKey:kavatarURL];
                    
                    [obj saveInBackground];
                    
                }];
                
            } else {
                [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
            }
            
        }];
    };
    
    MJWeakSelf;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSuccess) {
        
        if (photos.count > 0) {
            
            [LCCKUtil showProgressText:@"open client ..." duration:60.0f];
            
            UIImage *image = [photos lastObject];
            NSData *imageData = UIImagePNGRepresentation(image);
            
            AVFile *file = [AVFile fileWithData:imageData];
            
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
                if (succeeded) {
                    
                    AVUser *user = [AVUser currentUser];
                    
                    [user setObject:file.url forKey:kavatarURL];
                    
                    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                        if (!error) {
                            
                            [LCCKUtil hideProgress];
                            
                            updateWithContact(file.url);
                            
                            weakSelf.iconImageView.image = image;
                            
                            [LCCKUtil showNotificationWithTitle:@"头像更改成功" subtitle:nil type:LCCKMessageNotificationTypeSuccess];
                        } else {
                            [LCCKUtil hideProgress];
                            [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                        }
                    }];
                    
                } else {
                    [LCCKUtil hideProgress];
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
            }];
            
        }
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
